const assert = require('http-assert')
const jwt = require('jsonwebtoken')
const AdminUser = require('../models/AdminUser')

module.exports = opts => {


    return async (req, res, next) => {
        const token = String(req.headers.authorization || '').split(" ").pop()
        assert(token, 401, 'no jwt')

        const { id } = jwt.verify(token, req.app.get('secret'))
        assert(id, 401, 'jwt not has id')

        req.user = await AdminUser.findById(id)
        assert(req.user, 401, 'please log in')

        await next()
    }
}
